// 1、查询文章分类
$.ajax({
  type: "get",
  url: "/categories",
  success: (res) => {
    console.log(res);
    var html = template("listTpl", { data: res });
    // console.log(html);

    $("#typeList").html(html);
  },
});

// 2、添加文章分类
$(".addCata").on("submit", function () {
  var data = $(this).serialize();
  console.log(typeof data);
  $.ajax({
    type: "post",
    url: "/categories",
    data: data,
    success: (res) => {
      //   console.log(res);
      location.reload();
    },
  });
  return false;
});

// 3-1、修改文章分类
$("#typeList").on("click", ".edit", function () {
  console.log($(this).attr("data-id"));
  var id = $(this).attr("data-id");
  $.ajax({
    type: "get",
    url: `/categories/${id}`,
    success: (res) => {
      console.log(res);
      const html = template("editTpl", { data: res });
      $("#catalog").html(html);
    },
  });
});

// 3-2、提交修改信息
$("#catalog").on("submit", "#editForm", function () {
  var id = $(this).attr("data-id");
  var formdata = $(this).serialize();
  $.ajax({
    type: "put",
    url: `/categories/${id}`,
    data: formdata,
    success: (res) => {
      console.log(res);
      location.reload();
    },
  });
  return false;
});

// 4、全选与复选
$("#checkAll").on("change", function () {
  var isChecked = $(this).prop("checked");
  console.log(isChecked);
  $("tbody").find("input").prop("checked", isChecked);
  if (isChecked) {
    $("#deleteAll").css("display", "block");
  } else {
    $("#deleteAll").css("display", "none");
  }
});

$("tbody").on("click", "input", function () {
  var allcheck = $("tbody").find("input").length;
  var check = $("tbody").find("input:checked").length;
  if (check == allcheck) {
    $("#checkAll").prop("checked", "checked");
  } else {
    $("#checkAll").prop("checked", false);
  }
  if (check > 1) {
    $("#deleteAll").css("display", "block");
  } else {
    $("#deleteAll").css("display", "none");
  }
});
// 5、删除文章分类
$("#typeList").on("click", ".remove", function () {
  var id = $(this).attr("data-id");
  console.log(id);
  var remove = confirm("确定删除此分类？");
  if (remove) {
    $.ajax({
      type: "delete",
      url: `/categories/${id}`,
      success: (res) => {
        location.reload();
        console.log("删除成功");
      },
      error: (err) => {
        console.log(err);
      },
    });
  }
});
// 6、批量删除文章分类
$("#deleteAll").on("click", function () {
  var ids = [];
  var checked = $("tbody").find("input:checked");
  $.each(checked, (index, ele) => {
    // console.log($(ele).attr("data-id"));
    ids.push($(ele).attr("data-id"));
  });
  var str = ids.join("-");
  console.log(str);

  if (confirm("您确定要删除这些分类吗？")) {
    $.ajax({
      type: "delete",
      url: `/categories/${str}`,
      success: (res) => {
        console.log("删除成功");
        location.reload();
      },
      error: (err) => {
        console.log(err);
      },
    });
  }
});
